import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ShapeDrawer extends JFrame {
    private DrawArea drawArea = new DrawArea();
      public ShapeDrawer() {
        this.setSize(400, 400); //
               this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle(" 图形绘制器 "); //
                     this.add(drawArea, BorderLayout.CENTER);
       JComboBox<String> shapeSelector = new JComboBox<>(new String[]
                {" 正⽅形 ", "⻓⽅形 ", " 圆形 ", " 三⻆形 "});
                     this.add(shapeSelector, BorderLayout.NORTH);
            shapeSelector.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox) e.getSource();
                String shapeName = (String) cb.getSelectedItem();
                int size = 0; //
                boolean validInput = false; //
                while (!validInput) { //
                    String input = JOptionPane.showInputDialog(" 请输⼊ " + shapeName + " 的尺⼨:");
                    try {


                        size = Integer.parseInt(input); //
                        validInput = true;
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(null, " 输⼊⽆效，请输⼊⼀个整 数。 ");
                        drawArea.setShape(shapeName, size);

                    }}}


                 });

    }
          public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new ShapeDrawer().setVisible(true);
                }
              });
          }

    private static class DrawArea extends JPanel {
             private String shape = "正⽅形";
             private int size =100;
            public void setShape(String shape,int size) {
            this.shape = shape;
            this.size=size;
            this.repaint(); //
      }
        @Override
        //


     protected void paintComponent(Graphics g) {

          super.paintComponent(g);

          switch (shape) {
                case " 正⽅形 ":
                                       g.drawRect(50, 50, size, size);
                    break;
                case "⻓⽅形 ":
                             g.drawRect(50, 50, size*2, size);
                    break;
                case " 圆形 ":

                               g.drawOval(50, 50, size, size);
                    break;
                case " 三⻆形 ":
                    //
                                     int[] xPoints = {50+size/2, 50, 50+size};
                    int[] yPoints = {50, 50+size, 50+size};
                g.drawPolygon(xPoints, yPoints, 3);
                    break;

            }
        }
    }
            }